<template>
  <HeaderComponent v-if="showHeader" />
  <el-button type="text" class="back-button" @click="goBack">返回</el-button>
  <el-button type="text" class="back-button" @click="goOut">退出登录</el-button>
  <div class="user-info-container">
    <h2 class="user-info-title">个人信息</h2>

    <!-- 展示用户信息 -->
    <div v-if="UserVO" class="user-info-display">
      <div class="info-item">
        <label>用户名：</label>
        <span>{{ UserVO.name }}</span>
      </div>
      <div class="info-item">
        <label>手机号：</label>
        <span>{{ UserVO.telephone }}</span>
      </div>
      <div class="info-item">
        <label>用户类型：</label>
        <span>{{ UserVO.type }}</span>
      </div>
      <div class="info-item">
        <label>注册时间：</label>
        <span>{{ formatDate(UserVO.date) }}</span>
      </div>
    </div>

    <!-- 编辑用户信息按钮 -->
    <div class="button-container">
      <el-button type="primary" @click="showEditDialog">编辑用户信息</el-button>
    </div>

    <!-- 修改用户信息的弹框 -->
    <el-dialog v-model="editDialogVisible" title="修改用户信息" width="30%">
      <el-form :model="UserDTO" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="UserDTO.name" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="UserDTO.pwd" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import HeaderComponent from "@/components/HeaderComponent.vue";
import { LogOut } from "@/api";
import { onMounted, ref, reactive } from "vue";
import { GetUserInfo, UpdateUserInfo } from "@/api"; // 假设 API 方法已定义
import { ElMessage } from "element-plus";

export default {
  components: { HeaderComponent },
  setup() {
    const UserVO = ref(null); // 初始化为 null
    const showHeader = ref(true);
    const UserDTO = reactive({
      name: "",
      pwd: ""
    });
    const editDialogVisible = ref(false); // 控制弹框显示

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await GetUserInfo();
        console.log('GetUserInfo Response:', response); // 添加调试信息
        if (response.data.code === 200) {
          UserVO.value = response.data.data; // 正确赋值
          UserDTO.name = response.data.data.name; // 初始化表单数据
          UserDTO.pwd = response.data.data.pwd;
        } else {
          ElMessage.error("获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        ElMessage.error("请求失败，请稍后重试");
      }
    };

    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleString();
    };

    // 提交修改
    const handleUpdate = async () => {
      try {
        const response = await UpdateUserInfo(UserDTO);
        if (response.data.code === 200) {
          ElMessage.success("修改成功");
          await fetchUserInfo(); // 重新获取用户信息
          editDialogVisible.value = false; // 关闭弹框
          localStorage.setItem('username', UserDTO.name);
        } else {
          ElMessage.error(response.data.message || "修改失败");
        }
      } catch (error) {
        console.error("修改用户信息失败:", error);
        ElMessage.error("请求失败，请稍后重试");
      }
      showHeader.value = false;
      setTimeout(() => {
        fetchUserInfo(); // 页面加载时自动调用
        showHeader.value = true;
      }, 10)
    };

    // 显示编辑弹框
    const showEditDialog = () => {
      editDialogVisible.value = true;
    };

    // 页面加载时获取用户信息
    onMounted(() => {
      fetchUserInfo(); // 页面加载时自动调用
    });

    return {
      UserVO,
      UserDTO,
      editDialogVisible,
      handleUpdate,
      formatDate,
      showEditDialog,
      showHeader,
    };
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    async goOut() {
      try {
        const token = localStorage.getItem('token');
        if (token) {
          console.log('开始登出');
          console.log('token:', token);
          const response = await LogOut(token);
          console.log('Logout Response:', response);
        } else {
          console.warn('Token not found in localStorage');
        }
      } catch (error) {
        console.error('Logout Error:', error);
        alert('登出失败，请稍后再试');
      }
      localStorage.removeItem('token');
      localStorage.removeItem('type');
      this.$store.dispatch('logout');
      this.$router.push('/');
    }
  }
};
</script>

<style scoped>
.user-info-container {
  max-width: 600px;
  margin: 30px auto;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-info-title {
  text-align: center;
  color: #007bff;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.user-info-display {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
  font-size: 16px;
}

.info-item label {
  font-weight: 500;
  color: #333;
  margin-right: 10px;
}

.button-container {
  text-align: center;
  margin-top: 20px;
}

.btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.btn:hover {
  background-color: #0056b3;
}
</style>
